package 力扣._00周赛._376周赛.问题3;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;

class Solution {
    static boolean ishuiwen(int num) {
        String s = String.valueOf(num);
        for (int i = 0, j = s.length() - 1; i < j; i++, j--) {
            if (s.charAt(i) != s.charAt(j))
                return false;
        }
        return true;
    }
    int getmid(int avg){
        int i = 0,mid;
        while (avg + i < 1000000000 && !ishuiwen(avg + i)) i++;
        int j = 0;
        while (avg - j >= 1 && !ishuiwen(avg - j)) j++;
        if (i < j && ishuiwen(avg + i))
            mid = avg + i;
        else
            mid = avg - j;
        return mid;
    }


    public long minimumCost(int[] nums) {
        //平均值最近的回文数
        int n = nums.length;
        double sum = 0;
        for (int num : nums)
            sum += num;
        int avg = (int) (sum / nums.length);
        int mid1 = getmid(avg);
        int mid2 = getmid(avg+1);

        //System.out.println(mid + " " + avg);
        long cost1 = 0;
        for (int num : nums) {
            cost1 += Math.abs(mid1 - num);
        }
        long cost2 = 0;
        for (int num : nums) {
            cost2 += Math.abs(mid2 - num);
        }
        return Math.min(cost1,cost2);
    }

    public static void main(String[] args) {
        int[] nums = new int[]{101,102,105,108,124};
        long l = new Solution().minimumCost(nums);
        System.out.println(l);
        System.out.println(ishuiwen(11));
    }
}